package lumis.service.wsrp.producer;

import javax.persistence.NoResultException;

import lumis.doui.source.IDataProvider;
import lumis.doui.source.ISourceData;
import lumis.doui.source.TabularData;
import lumis.doui.source.TabularSource;
import lumis.doui.source.field.ITabularSourceField;
import lumis.portal.PortalException;
import lumis.portal.UnexpectedException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.service.wsrp.common.WSRPUtils;
import lumis.util.ITransaction;

import com.sun.portal.wsrp.producer.ProducerException;

/**
 * {@link IDataProvider} responsible for populating a {@link TabularData} with
 * the {@link ProducerImpl} associated with the current service instance.
 * 
 * @version $Revision: 12680 $ $Date: 2011-03-04 15:32:40 -0300 (Fri, 04 Mar 2011) $
 * @since 5.5.0
 */
public class ProducerConfigurationInterfaceDataProvider implements IDataProvider<TabularSource<ITabularSourceField>>
{
	/**
	 * {@inheritDoc}
	 */
	public void loadData(SessionConfig sessionConfig, TabularSource<ITabularSourceField> source, ITransaction transaction) throws PortalException
	{
		String serviceInstanceId = source.getDouiContext().getRequest().getServiceInstanceConfig().getId();

		// get the producer associated with current service instance
		ProducerImpl producer;
		try
		{
			producer = (ProducerImpl) ManagerFactory.getEntityManager().createNamedQuery(ProducerImpl.NAMED_QUERY_FIND_PRODUCER_BY_NAMESPACE).setParameter("namespace", serviceInstanceId)
					.getSingleResult();
		}
		catch (NoResultException e)
		{
			producer = null;
		}

		// if there is a producer, we populate the TabularData with its values
		if (producer != null)
		{
			try
			{
				ISourceData row = source.getData().addRow();
				row.put("producerKey", producer.getProducerKey());
				row.put("serviceInstanceId", producer.getNamespace());
				row.put("version", producer.getVersion());
				row.put("enabled", producer.isEnabled());
				row.put("httpAuthenticator", producer.getHttpAuthenticator());
				row.put("requiresRegistration", producer.requiresRegistration());
				row.put("supportsInbandRegistration", producer.inbandRegistrationSupported());
				if(producer.inbandRegistrationSupported())
				{
					row.put("maxInbandLifetime", (Long)(producer.getMaxInbandLifetime() / WSRPUtils.MILISSECONDS_IN_A_DAY));
				}
				
			}
			catch (ProducerException e)
			{
				throw new UnexpectedException(e);
			}
		}
	}
}
